package com.myself.community.controller;

import com.myself.community.annotation.LoginRequired;
import com.myself.community.entity.Event;
import com.myself.community.entity.User;
import com.myself.community.event.EventProducer;
import com.myself.community.service.LikeService;
import com.myself.community.utils.Code;
import com.myself.community.utils.CommunityUtil;
import com.myself.community.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LikeController {

    @Autowired
    private LikeService likeService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducer eventProducer;

    /**
     * 点赞或取消赞操作
     * @param entityType
     * @param entityId
     * @param entityUserId
     * @return
     */
    @LoginRequired
    @PostMapping("/like")
    public String like(int entityType, int entityId, int entityUserId,int postId) {
        User user = hostHolder.getUser();

        // 点赞
        likeService.like(user.getId(), entityType, entityId, entityUserId);

        // 数量
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        // 状态
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);
        // 返回的结果
        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);

        //点赞成功后
        //触发点赞事件：点赞发送消息，取消赞就不用处理了
        if(likeStatus==1){
            Event event = new Event()
                    .setTopic(Code.TOPIC_LIKE)
                    .setUserId(hostHolder.getUser().getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityUserId)
                    .setData("postId", postId);//帖子id

            //生产者处理事件:发送消息到消息队列
            eventProducer.sendEvent(event);
        }

        return CommunityUtil.getJSONString(Code.OK, null, map);
    }

}
